/**
 * Created by hiephn on 2014/08/28.
 */
define('http',['jquery', 'modals'], function($, modals) {
    function request(method, url, data, options) {
        if (!data) {
            data = {};
        }
        var ajaxOptions = {
            url: url,
            method: method,
            data: data,
            error: function(jqXHR) {
                if (options.error) {
                    options.error(jqXHR);
                } else {
                    handleError(jqXHR);
                }
            }
        };
        options.xhrFields = {
            withCredentials: true
        };
        for (var i in options) {
            ajaxOptions[i] = options[i];
        }
        var ajax = $.ajax(ajaxOptions);
        if (options.success) {
            ajax.then(options.success);
        }
        return ajax;
    }
    function handleError(jqXHR) {
        var msg;
        if (jqXHR.status == 401) {
            msg = "Lỗi đăng nhập. " + jqXHR.responseJSON.message;
        } else if (jqXHR.status == 500) {
            msg = "Lỗi server. " + jqXHR.responseJSON.message;
        } else if (jqXHR.status == 409 || jqXHR.status == 404) {
            msg = "Lỗi. " + jqXHR.responseJSON.message;
        } else if (jqXHR.status == 400) {
            msg = "Lỗi."
                + jqXHR.responseJSON.message;
        } else if (jqXHR.status == 0) {
            msg = "Không thể kết nối tới server.";
        } else {
            msg = "Lỗi. " +
                "Error code: " + jqXHR.status;
            if (jqXHR.responseJSON != null) {
                msg += ". " + jqXHR.responseJSON.message;
            }
        }
        modals.info(msg);
    }

    return {
        get: request.bind(null, "GET"),
        put: request.bind(null, "PUT"),
        post: request.bind(null, "POST"),
        delete: request.bind(null, "DELETE")
    }
})